
const cartbox = document.querySelector('.cart_shopping')
let listinfo = {
  current: 1,
  pagesize: 9,
  sort: 'ASC'

}
var arr = [undefined, undefined, undefined,0,true]
let listAll = []
let footlist = []

let username = getQueryVariable('name')
if(!username){
  // $('.top_left_hide')
}
if (username) {
  $('.top_left').css('display', 'none')
  $('.top_left_hide').css('display', 'block')
  $('.top_left_hide >li > p').html(username)

  // 点击退出按钮,退出账号,但是back键还可以退回来 待解决.....
  $('.top_left_hide a').on('click', function () {
    $('.top_left').css('display', 'block')
    $('.top_left_hide').css('display', 'none')
    window.location.href = "http://www.yjf.com:8080/page/list.html"
  })
}
// 渲染完页面后的回调事件里绑定事件
function ajaxEvent() {
  // 商品移入显示加入购物车
  $('.layout-center').on('mouseenter ', "li", function (e) {
    e = e || window.event
    $(this).find('.commit_new').css('display', 'block')
  })
  $('.layout-center').on('mouseleave', "li", function (e) {
    e = e || window.event
    $(this).find('.commit_new').css('display', 'none')
  })
}

// 获取localStorage里面的数据放到cartList 初始化購物車列表
fillCartList()
function fillCartList() {
  cartList = []
  for (var i = 0; i < localStorage.length; i++) {
    var key = localStorage.key(i)

    cartList.push(JSON.parse(localStorage[key]))
  }
  bindCart()
}
//  渲染购物车
function bindCart() {
  // 如果购物车里没货,不执行
  if (!cartList.length || !username) {
    cartbox.innerHTML = `
           <div class='kong'>
            购物车里还没有商品,<br>
            快去挑选心爱的商品吧~
           <div>
         `
  } else {
    let cartList = []
    for (var i = 0; i < localStorage.length; i++) {
      var key = localStorage.key(i)

      cartList.push(JSON.parse(localStorage[key]))
    }
    let totalPrice = 0
    let num = 0
    // 渲染num 数量
    if (cartList.length) {

      $('.num').css('display', 'block').html(cartList.length)
    }
    cartList.forEach(e => {
      let unitPrice = e.deal_global ? e.deal_global.price_home : e.deal_group.price_dis

      totalPrice += (e.report_number + 1) * unitPrice
      num += parseInt(e.report_number + 1)
    })

    var str = template('cart_tmp', {
      list: cartList,
      num: num,
      price: totalPrice

    })
    cartbox.innerHTML = str
  }
}
// 各种移入显示
hoverXianshi('.me_jm')
hoverXianshi('.right_more')
hoverXianshi('.shopping-cart')


// 获取数据
// 交互
Ajax()
function Ajax() {
  $.ajax({
    url: '/jm/GetHomeTodayLists/100/1',
    success: function (res) {
      let { message, list } = JSON.parse(res)
      if (message != true) {
        console.log('获取数据失败');
      }
      listAll.push(...list)
      footlist.push(...list)
    }
  })



  $.ajax({
    url: '/jm/GetHomeTodayLists/100/101',
    success: function (res) {
      let { message, list } = JSON.parse(res)
      if (message != true) {
        console.log('获取数据失败');
      }
      listAll.push(...list)
      footlist.push(...list)
      title(list)
      fliterClick()
      filter()
    }
  })
}
//类别,给元素打上记号
function title(list) {
  let arr = []
  // 获取类别标识
  list.forEach(item => {
    if (!arr.includes(item.deal_category))
      arr.push(item.deal_category)
  })
    //设置自定义属性当标识
    ;[...$('.filter_con').eq(0).find('li').first().nextAll()].forEach((item, index) => {
      $(item).attr('data_lb', arr[index])
    })
  // ["global", "media", "product", "retail_global"] 
  // 对应着 全球 流行 精品 小众
  // 获取品牌标识
  arr = []
  for (let key in list[0].deal_state) {
    arr.push(key)
  }
  ;[...$('.filter_con').eq(1).find('li').first().nextAll()].forEach((item, index) => {
    $(item).attr('data_lb', arr[index])
  })

  ;[...$('.filter_con').eq(2).find('li').first().nextAll()].forEach((item, index) => {
    $(item).attr('data_min', parseInt($(item).text().split('-')[0]))
    $(item).attr('data_max', parseInt($(item).text().split('-')[1]))
  })
}


// 分页器
function bindPagi(lsit) {
  new Pagination('.pagination', {
    total: lsit,
    current: listinfo.current,
    pagesize: listinfo.pagesize,
    first: '首页',
    prev: '上一页',
    next: '下一页',
    last: '尾页',
    go: '跳转',
    change(num) {
      listinfo.current = num
      bindHtml(num)
    }
  })
}

function bindHtml(num) {
  let bindlist = footlist.slice((num - 1) * 10, (num - 1) * 10 + listinfo.pagesize)
  let str = template('tmp', {
    list: bindlist,

  })
  $('.content_body').html(str)
}

// 筛选点击事件 点击将筛选条件添加到arr里
function fliterClick() {
    // 返回首页
  $('.log').on('click','a',function(){
      window.location.href = "http://www.yjf.com:8080/page/index.html?name="+username
  })
  $('.filter_con').on('click', 'li', function (e) {
    // 添加颜色
    $(this).siblings().removeClass()
    $(this).addClass('active')
    let index = $(this).parent().parent().parent().index()
    arr[index] = $(this).attr('data_lb')
    if(index == 2 ){
      arr[2] = { price_max: $(this).attr('data_max'), price_min: $(this).attr('data_min') }
    }
    filter()
  })
  $('.sort > ul > li').on('click',function(){
    arr[3] = $(this).index()
    arr[4] = !arr[4]
    filter()
  })
 
}

// 通过筛选条件arr 筛选
function filter() {
  // 一次筛选
  
  if (arr[0] == undefined) {
    footlist = listAll.map(e=>{ return e})

  } else {
    footlist = listAll.filter(e => {
      return e.deal_category == arr[0]
    })
  }
  // 第二次筛选
  if (arr[1] == undefined) {
    // 不用筛选
  } else {
    footlist = footlist.filter(e => {
      return e.deal_state[arr[1]] == true
    })
  }
  // 第三次筛选
  if (arr[2] == undefined || (arr[2].price_max == undefined && arr[2].price_min == undefined)) {
    // 不用筛选
  } else {
    footlist = footlist.filter(e => {
      if(arr[2].price_max == 'NaN'){
        if(e.deal_global){
          return e.deal_global.price_home > arr[2].price_min
        }else{
          return e.deal_group.price_dis > arr[2].price_min 
        }
      }else{
        if(e.deal_global){
          return e.deal_global.price_home > arr[2].price_min && e.deal_global.price_home < arr[2].price_max
        }else{
          return e.deal_group.price_dis > arr[2].price_min && e.deal_group.price_dis  < arr[2].price_max
        }
      }
    })
  }
  // 判断排序方式
  if(arr[3] == 0){
    
  }else if(arr[3] == 1){
    footlist.sort((a,b) =>{
      return a.deal_num - b.deal_num
    })
  }
  else if(arr[3] == 2){
    footlist.sort( (a,b) =>{
        var priceA = a.deal_global ? 'deal_global.price_home' : 'deal_group.price_dis'
        var priceB = b.deal_global ? 'deal_global.price_home' : 'deal_group.price_dis'
        let priceArr = priceA.split('.')
        let priceBrr = priceB.split('.')
        return a[priceArr[0]][priceArr[1]] - b[priceBrr[0]][priceBrr[1]]
    })
  }
  //判断排序类型
  if(arr[3] != 0 && arr[4] == true){
    footlist.reverse()
  }

  if (!footlist.length) {
    $('.content_body ').css('display', 'none')
    $('.pagination').css('display', 'none')
    $('.content_hide').css('display', 'block')
  } else {
    $('.content_body ').css('display', 'block')
    $('.pagination').css('display', 'block')
    $('.content_hide').css('display', 'none')
    listinfo.current = 1
    bindPagi(footlist.length)
  }

}
// 移入显示加入购物车
moveShow()
function moveShow(){
  $('.content_body').on('mouseenter ', "li", function (e) {
    e = e || window.event
    $(this).find('.commit_new').css('display', 'block')
})
  $('.content_body').on('mouseleave', "li", function (e) {
    e = e || window.event
    $(this).find('.commit_new').css('display', 'none')
})
//避免渲染时候的重新绑定事件,先解绑以前绑定的点击事件   
  $('.content_body').off('click', '.commit_btn')
// 加入购物车按钮绑定事件
  $('.content_body').on('click', '.commit_btn', function (e) {
    e = e || window.event
    e.stopPropagation()
    // 如果没登录,跳转到登录页面
    if(!username){
        window.location.href="http://www.yjf.com:8080/page/login.html"
    }
    // 点击商品的index
    let index = $(this).parent().parent().index()
    let frg = false
    for (var i = 0; i < localStorage.length; i++) {
        if (index == localStorage.key(i)) {
            frg = true
        }
    }
    if (frg == true) {
        let zancun = JSON.parse(localStorage[index])
        // 数量+1
        zancun.report_number++
        // 再将数据封装到local里面
        localStorage.setItem(index, JSON.stringify(zancun));

    } else if (frg == false) {
        localStorage.setItem(index, JSON.stringify(footlist[index]));
    }
    console.log(JSON.parse(localStorage[index]));
    fillCartList()
    donghua(e.pageX,e.pageY)
})
        // 公共函数 去详情页
        goDetails('.content_body',footlist)
        // 公共函数绑定去购物车页面的按钮
        goCart()
}

bingNav()
hide_nav('nav')
// 搜索
const inp = document.querySelector('.inpt_search')
const ul = document.querySelector('.ul_search')
// 1. 绑定事件
inp.addEventListener('input', function () {

  const str = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=32646,1446,32532,32327,32351,32046,32115,31321,32618,32503,22159&wd=' + this.value + '&req=2&bs=%E7%88%B1%E5%A5%87%E8%89%BA&csor=6&cb=fn&_=1598517558259'
  const script = document.createElement('script')
  script.src = str
  document.body.appendChild(script)
  script.remove()
})

function fn(res) {
  if (!res.g) {
    ul.style.display = 'none'
    return
  }
  let str = ''
  res.g.forEach(item => {
    str += `
      <li>${item.q}</li>
    `
  })
  ul.innerHTML = str
  ul.style.display = 'block'
  // 绑定点击事件
  $(ul).on('click', 'li', function () {
    $('.inpt_search').val(this.innerHTML)
    $('.ul_search').slideUp()
  })
}


